package com.main.controller;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.generico.dao.ctg.CtgProveedorDao;
import com.generico.dto.ctg.CtgProveedor;
import com.main.dao.CompraDao;
import com.main.dao.UserDAO;
import com.main.java.Compra;
import com.main.java.User;
import com.web.util.GenericoUtil;


@Controller
@RequestMapping("/empleado")
public class CompraProveedorController extends BaseController{
	
	@Autowired
	private CompraDao compraDao;
	
	@Autowired
	private CtgProveedorDao ctgProveedorDao;
	
	@Autowired
	private UserDAO userDAO ;
	
	private static Long uploadMaxSize;

	@RequestMapping(value = "/compraProveedor")
	public String compraProveedor(HttpServletRequest request, ModelMap model){
		model.put("proveedores", JSONArray.fromObject(ctgProveedorDao.getAllActivesAsArray()));
		model.put("compras", JSONArray.fromObject(compraDao.getAllActivesAsArray()));
		model.put("usuarioId", GenericoUtil.getSgdUsuarioIdFromAcegi());
		model.put("userName", GenericoUtil.getUserName());
		model.put("rol", GenericoUtil.getRol());
		return "empleado/compraProveedor";
	}
	
	@RequestMapping(value = "/compraProveedor/save", method = {RequestMethod.POST})
	public void save(HttpServletResponse response,
			@ModelAttribute(value = "compra") Compra compra,
			@ModelAttribute(value = "proveedorId") Long proveedorId,
			@RequestParam(value="uploadFile") CommonsMultipartFile uploadFile) {
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			
			
			
			if(compra != null){
				User usuario = new User();
				usuario = userDAO.getUserById(GenericoUtil.getSgdUsuarioIdFromAcegi());
				compra.setUsuario(usuario);
				CtgProveedor ctgProveedor = new CtgProveedor();
				ctgProveedor = ctgProveedorDao.encontrarCtgProveedorPorId(proveedorId);
				compra.setCtgProveedor(ctgProveedor);
				result = compraDao.guardarCompra(compra, getKycUploadMaxSize(), uploadFile);
				result.put("ctgProductoId", compra.getCompraId());
				result.put(SUCCESS, true);
				result.put(MESSAGE, "Datos Actualizados");
				List<Object[]> list = compraDao.getAllActivesAsArray();
				for (int index = 0; index < list.size(); index++) {
					if(compra.getCompraId().equals(list.get(index)[0])){
						result.put("comprasIndex", index);
						break;
					}
				}
				result.put("compras", JSONArray.fromObject(list));
			}else{
				result.put(FAILURE, true);
				result.put(MESSAGE, GenericoUtil.ERROR_MESSAGE);
			}
		}catch(Exception e){
			result.put(FAILURE, true);
			result.put(MESSAGE, GenericoUtil.getExceptionMessage(e));
		}
		serializeObject(result, response);
	}
	
	@RequestMapping(value = "/delete", method = {RequestMethod.POST})
	public void delete(HttpServletResponse response,
			@RequestParam Long compraId) {
		Map<String, Object> result = new HashMap<String, Object>();
		try{
			compraDao.eliminarCompra(compraId);
			result.put(SUCCESS, true);
			result.put(MESSAGE, "Dato Compra Eliminado");
			result.put("compras", JSONArray.fromObject(compraDao.getAllActivesAsArray()));
		}catch(Exception e){
			result.put(FAILURE, true);
			result.put(MESSAGE, GenericoUtil.getExceptionMessage(e));
		}
		serializeObject(result, response);
	}
	
	private Long getKycUploadMaxSize(){
		if(uploadMaxSize == null) uploadMaxSize = Long.valueOf(GenericoUtil.trimToZero(GenericoUtil.FILE_UPLOAD_MAX_SIZE));
		return uploadMaxSize;
	}

	
	@RequestMapping(value = "/viewProductoImagen", method = {RequestMethod.GET, RequestMethod.POST})
	public void viewFile(HttpServletResponse response, @RequestParam("codigo") String codigo) {
		try {
			Long compraId = new Long(StringUtils.defaultIfEmpty(codigo, "0"));
			List<Compra> compraIma = compraDao.getCtgCompras(compraId);
			if (!GenericoUtil.isEmptyList(compraIma)) {
				for (Compra compIma : compraIma) {
					
					if (compIma == null || compIma.getCompra_imagen() == null || compIma.getCompra_imagen().length == 0) {
						response.getWriter().write("<h1>DOCUMENTO NO ENCONTRADO</h1>");
						return;
					}
					byte[] archivo = compIma.getCompra_imagen();

					response.setHeader("Content-Length", String.valueOf(archivo.length));

					response.setContentType("image/jpg");

					ServletOutputStream out = response.getOutputStream();
					ByteArrayInputStream bais = new ByteArrayInputStream(archivo);

					byte[] outputByte = new byte[2048];
					while (bais.read(outputByte, 0, 2048) != -1) out.write(outputByte, 0, 2048);
					bais.close();
					out.flush();
					out.close();
					
				}
			}
			
			
			
			
			
			
		} catch (Exception e) {
			logger.error("Problemas recuperando informacion de Imagen", e);
			try {
				response.setContentType("text/html");
				response.getWriter().write("<h1>DOCUMENTO NO ENCONTRADO</h1>");
			} catch (IOException e1) {
				logger.error("Error", e1);
			}
		}
	}
	
}
	
	
	
	
	

